import dayjs from '../../utils/dayjs'
import {
  Toast,
  Loading
} from "../../utils/util.js";
import echarts from '../../ec-canvas/echarts'
let chartSearch = {}
let chart = null
async function initChartOne(canvas, width, height, dpr) {
  chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // 像素
  });
  console.log(chartSearch, 666)
  canvas.setChart(chart);
  const _ = wx.cloud.database().command;
  const res = await wx.cloud.database().collection('todoList').where({
    foodTimeStr: _.and(_.gt(chartSearch.startTime), _.lt(chartSearch.endTime)),
    userId: wx.getStorageSync('uid'),
    tableType: "recipe"
  }).get()
  console.log(res, '我要')
  const groupedData = res.data.reduce((acc, obj) => {
    const key = obj.foodTypeName;
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
  console.log(groupedData, '外部')
  let optionArray = [];
  Object.keys(groupedData).forEach(item => {
    console.log(groupedData[item], 'groupedData[item]')
    let arr = groupedData[item].map(items => items.foodRlSum)
    let prices = arr.reduce(function (accumulator, currentValue) {
      return accumulator + currentValue;
    }, 0)
    optionArray.push({
      name: item,
      value: prices
    })
  })
  console.log(optionArray, '外部2')
  var option = {
    title: {
      text: `饮食热量占比`,
      left: 'center',
      top: "0"
    },
    tooltip: {
      trigger: 'item',
      formatter: `{a} <br/>{b}: {c} <br/>({d}%)`, // 默认显示数值和百分比
    },
    legend: {
      left: 'center',
      top: '50px'
    },
    label: {
      show: true,
      formatter: '{b}: {c} \n({d}%)', // 显示名称、数值、百分比
      position: 'outside',
      color: 'black'
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '40%',
        center: ['50%', '60%'],
        data: [...optionArray],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  chart.setOption(option);
  console.log(chart)
  return chart;
}
// pages/eat/eat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    recipeList: [],
    tjFoodList: [],
    tjSuggestion: "",
    foodList: [],
    modalName: '',
    ishidden: false,
    ec: {
      onInit: {}
    },
    searchTime: "",
    form: {
      foodName: "",
      foodType: "",
      foodTypeName: "",
      foodWeight: 0,
      foodTime: dayjs(new Date()).format('YYYY-MM-DD'),
      foodTimeStr: dayjs(new Date()).valueOf(),
      foodRl: 0,
      foodRlSum: 0
    }
  },
  hideModal() {
    this.setData({
      modalName: '',
      form: {
        foodName: "",
        foodType: "",
        foodTypeName: "",
        foodWeight: 0,
        foodTime: dayjs(new Date()).format('YYYY-MM-DD'),
        foodTimeStr: dayjs(new Date()).valueOf(),
        foodRl: 0,
        foodRlSum: 0
      }
    })
  },
  showModal(e) {
    this.setData({
      modalName: "bottomModal",
      form: {
        ...this.data.form,
        foodType: e.detail.value,
        foodTypeName: this.data.recipeList.filter(item => item.value == e.detail.value)[0]['key'],
        foodRl: e.detail.rl
      }
    })
  },
  async getFoodList() {
    const res = await wx.cloud.database().collection('todoList').where({
      userId: wx.getStorageSync('uid'),
      tableType: "recipe"
    }).get()
    let tsj = res.data;
    // 使用 reduce 方法对数组进行分组
    const groupedData = res.data.reduce((acc, obj) => {
      const key = obj.foodTime;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    let resData = []
    Object.keys(groupedData).forEach(item => {
      resData.push({
        time: item,
        data: groupedData[item]
      })
    })

    //推荐算法
    const groupedData1 = tsj.reduce((acc, obj) => {
      const key = obj.foodTypeName;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    console.log(groupedData1, 'foodTypeName')
    let arr_ = []
    Object.keys(groupedData1).forEach(item => {
      arr_.push({
        key: item,
        value: groupedData1[item].map(item => item.foodRlSum).reduce(function (accumulator, currentValue) {
          return accumulator + currentValue;
        }, 0)
      })
    })
    console.log(arr_, 'arr_')
    let minCateObj = arr_.reduce((min, obj) => {
      return obj.value < min.value ? obj : min;
    }, arr_[0])
    let tjFoodList = wx.getStorageSync('dictList').filter(item => item.dictValue == 'recipe')[0]['dictJson'].filter(e => e.key == minCateObj['key'])[0]['tjList']
    let str = "";
    arr_.forEach(i => {
      str = str + `${i.key}热量：${i.value}大卡,`
    })

    this.setData({
      foodList: [...resData],
      tjFoodList,
      tjSuggestion: `由历史数据计算可知，您在各饮食分布中${str}其中${minCateObj['key']}占比略低，所以为您推荐以下食谱，以保证饮食平衡。`
    })
  },
  getFoodToWeek() {
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }
    this.setData({
      "ec.onInit": initChartOne,
    })
  },
  async reLoadDateChart() {
    const _ = wx.cloud.database().command;
    const res = await wx.cloud.database().collection('todoList').where({
      foodTimeStr: _.and(_.gt(chartSearch.startTime), _.lt(chartSearch.endTime)),
      userId: wx.getStorageSync('uid'),
      tableType: "recipe"
    }).get()
    const groupedData = res.data.reduce((acc, obj) => {
      const key = obj.foodTypeName;
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
    let optionArray = [];
    Object.keys(groupedData).forEach(item => {
      let arr = groupedData[item].map(items => parseInt(items.foodRlSum))
      let prices = arr.reduce(function (accumulator, currentValue) {
        return accumulator + currentValue;
      }, 0)
      optionArray.push({
        name: item,
        value: prices
      })
    })
    var option = {
      title: {
        text: `饮食热量占比`,
        left: 'center',
        top: "0"
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c}<br/> ({d}%)' // 默认显示数值和百分比
      },
      legend: {
        left: 'center',
        top: '50px'
      },
      label: {
        show: true,
        formatter: '{b}: {c} \n({d}%)', // 显示名称、数值、百分比
        position: 'outside',
        color: 'black'
      },
      series: [
        {
          name: '占比',
          type: 'pie',
          radius: '40%',
          center: ['50%', '60%'],
          data: [...optionArray],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    chart.setOption(option);
  },
  getRecipeList() {
    this.setData({
      modalName: "bottomModal1",
    })
  },
  getTjFoodList() {
    this.setData({
      modalName: "bottomModal2",
    })
  },
  inputChange(e) {
    this.setData({
      'form.foodWeight': parseInt(e.detail.value),
      'form.foodRlSum': this.__data__.form.foodRl * parseInt(e.detail.value) / 100,
    })
  },
  formSubmit(e) {
    let that = this;
    if (e.detail.value.foodName == "") {
      Toast("none", this.data.form.foodTypeName + "不能为空");
      return;
    }
    if (this.data.form.foodWeight == 0) {
      Toast("none", "重量必须大于0");
      return;
    }
    let formDate = {
      ...this.data.form,
      foodName: e.detail.value.foodName
    };
    console.log(formDate)
    wx.cloud.database().collection('todoList').add({
      data: {
        ...formDate,
        tableType: 'recipe',
        userId: wx.getStorageSync('uid'),
      },
      success(res) {
        Toast("none", "添加成功");
        that.hideModal()
      },
      fail(res) {
        Toast("none", "添加失败");
      },
    })
  },
  reduceWeek() {
    this.setData({
      searchTime: `${dayjs(new Date(this.data.searchTime.split(' - ')[0])).subtract(1, "week").format('YYYY/MM/DD')} - ${dayjs(new Date(this.data.searchTime.split(' - ')[1])).subtract(1, "week").format('YYYY/MM/DD')}`,
      "ec.onInit": {}
    })
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }
    console.log(66)
    this.reLoadDateChart()
  },
  addWeek() {
    this.setData({
      searchTime: `${dayjs(new Date(this.data.searchTime.split(' - ')[0])).add(1, "week").format('YYYY/MM/DD')} - ${dayjs(new Date(this.data.searchTime.split(' - ')[1])).add(1, "week").format('YYYY/MM/DD')}`,
      "ec.onInit": {}
    })
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }
    this.reLoadDateChart()
  },
  switchTab(e) {
    console.log(e)
    let tab = e.currentTarget.id
    if (tab === 'tableft') {
      this.setData({
        currentTab: 0
      })
    } else if (tab === 'tabright') {
      this.setData({
        currentTab: 1
      })
      this.getAddSportStatus()
    }
  },
  async getAddSportStatus() {
    const res = await wx.cloud.database().collection('todoList').where({
      sportTime: dayjs(new Date()).format('YYYY-MM-DD'),
      userId: wx.getStorageSync('uid'),
    }).get()
    console.log(res)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      recipeList: wx.getStorageSync('dictList').filter(item => item.dictValue == 'recipe')[0]['dictJson'] ?? [],
      searchTime: `${dayjs().startOf("week").format('YYYY/MM/DD')} - ${dayjs().endOf("week").format('YYYY/MM/DD')}`,
    })
    chartSearch = {
      startTime: dayjs(new Date(this.data.searchTime.split(" - ")[0])).valueOf(),
      endTime: dayjs(new Date(this.data.searchTime.split(" - ")[1])).valueOf(),
    }

    this.getFoodList()
    this.getFoodToWeek()

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})